package com.kadron.newsletter;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import com.kadron.common.KConst;
import com.kadron.dao.KNewsletterDAO;
import com.kadron.entity.NewsLetter;
import com.kadron.exceptions.KPersistenceException;
import com.kadron.manager.KMessageManager;

@AutoCreate
@Name("kNewsletterManager")
@Scope(ScopeType.PAGE)
public class KNewsletterManager extends KMessageManager implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4184026689307942094L;

	private static final Log log = LogFactory.getLog(KNewsletterManager.class);
	
	private NewsLetter newsletter; 
	
	@In
	private KNewsletterDAO newsletterDAO;
	
	@Create
	public void init() {
		Long newsId = (Long) Component.getInstance("newsletterId");
		if (newsId == null) {
			newsId = new Long(0);
		}
		if (newsId > 0) {
			newsletter = (NewsLetter) newsletterDAO.find(newsId, NewsLetter.class);
		} else {
			newsletter = new NewsLetter();
		}
	}
	
	public String save() {
		if (newsletter == null || newsletter.isProcessed()) {
			bad(KConst.BAD_THING);
			return null;
		}
		if (log.isDebugEnabled()) {
			log.debug("Save News newsletterId="+newsletter.getId());
		}
		try {			
			newsletterDAO.update(newsletter);
			good();
			return "newsletter";
		} catch (KPersistenceException e) {
			if (log.isErrorEnabled()) {				
				log.error("KPersistenceException");
			}
			bad(KConst.BAD_THING);			
		}
		return null;
	}

	public NewsLetter getNewsletter() {
		return newsletter;
	}

	public void setNewsletter(NewsLetter newsletter) {
		this.newsletter = newsletter;
	}
}
